package com.ruitaowang.wap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruitaowang.core.domain.*;
import com.ruitaowang.goods.service.*;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;

@RestController
public class APIWapGoodsController extends BaseController {

    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
    
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsSearchService goodsSearchService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private GoodsAlbumService goodsAlbumService;
    @Autowired
    private RebateRatioService rebateRatioService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private DistrictService districtService;
    @Autowired
    private CollectionService collectionService;
    @Autowired
    private GoodsTypeCustomService goodsTypeCustomService;
    @Autowired
    private CategoryService categoryService;
    
    //带优惠券相册图片和评论数的商品列表
    @RequestMapping(value = "/api/wap/coupon/goods/custom", method = RequestMethod.GET)
    public String findGoodsCooupon(Goods goods, int page) {
        goods.setPage(page);
        if (!ObjectUtils.isEmpty(goods.getSidx())) {
            goods.setOrderBy(goods.getSidx() + " " + goods.getSord() + "," + goods.getOrderBy());
        }
        List listOut =  new ArrayList();
        List<Goods>goodsList=goodsService.selectForPage(goods);
        for (Goods g:goodsList){
            HashMap map = new HashMap();
            map.put("goods",g);
            GoodsAlbum goodsAlbum = new GoodsAlbum();
            goodsAlbum.setGoodsId(g.getGoodsId());
            goodsAlbum.setImageType((byte)1);
            List<GoodsAlbum> goodsAlbums=goodsAlbumService.select(goodsAlbum);
            if (!ObjectUtils.isEmpty(goodsAlbums)){
                map.put("goodsAlbum",goodsAlbums.get(0));
            }else {
                map.put("goodsAlbum","");
            }
            Coupon coupon =new Coupon();
            coupon.setCompanyId(g.getGoodsProviderId());
            coupon.setGoodsId(g.getGoodsId());
            coupon.setCouponType((byte)2);
            List<Coupon> coupons=couponService.select(coupon);
            if (!ObjectUtils.isEmpty(coupons)){
                map.put("coupon",coupons.get(0));
            }else {
                map.put("coupon","");
            }
            listOut.add(map);
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(goods.getRecords());
        o.setTotal(goods.getTotal());
        return this.renderJson(o);
    }
    
    @RequestMapping(value = "/api/wap/goods", method = RequestMethod.GET)
    public String listForWap(Goods goods, int page,@RequestHeader(value="headId",required = false) String userId) {
        goods.setPage(page);
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser user = sysUserService.selectByPK(Long.parseLong(userId));
        if (ObjectUtils.isEmpty(goods.getRows())||goods.getRows()==Integer.MAX_VALUE){
            goods.setRows(12);
        }
        List<Goods> listOut=new ArrayList<>();
        if (!ObjectUtils.isEmpty(goods.getSidx())) {
            goods.setOrderBy(goods.getSidx() + " " + goods.getSord() + "," + goods.getOrderBy());
        }
        Company company=companyService.selectByCompanyStaff(user.getId());
        if (!ObjectUtils.isEmpty(company)){
            if (ObjectUtils.isEmpty(goods.getGoodsProviderId())){
                goods.setGoodsProviderId(company.getCompanyId());
            }
            listOut = goodsSearchService.searchForPage(goods);
        }

        MsgOut o = MsgOut.success(listOut);
        o.setRecords(goods.getRecords());
        o.setTotal(goods.getTotal());
        return this.renderJson(o);
    }
    
    /**
     * @api {get} /api/wap/searchGoods 公众号-首页和店铺内搜素商品
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/searchGoods
     * @apiName searchGoods
     * @apiGroup Goods
     * @apiParam {String} goodsName 商品信息.
     * @apiParam {Int} page 第几页.
     * @apiParam {Long} userId 用户Id（headId）.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     */
    @RequestMapping(value = "/api/wap/searchGoods", method = RequestMethod.GET)
    public String searchGoods(Goods goods,int page,@RequestHeader(value = "headId", required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        goods.setPage(page);
        goods.setGoodsOnline((byte) 1);
        List<Goods> goodsList = goodsSearchService.searchForPage(goods);
        MsgOut o = MsgOut.success(goodsList);
        o.setRecords(goods.getRecords());
        o.setTotal(goods.getTotal());
        return this.renderJson(o);
    }
    
    @RequestMapping(value = "/api/wap/goods/{goodsProviderId}", method = RequestMethod.GET)
    public String wapFindGoods(@PathVariable("goodsProviderId") Long goodsProviderId) {
        Goods goods = new Goods();
        goods.setGoodsProviderId(goodsProviderId);
        MsgOut o = MsgOut.success(goodsService.select(goods));
        return this.renderJson(o);
    }
    
    @RequestMapping(value = "/api/wap/goods/get/{goodsId}", method = RequestMethod.GET)
    public String wapFindGoodsUpdate(@PathVariable("goodsId") Long goodsId) {
        Map out = new HashMap();
        Goods goods = goodsService.selectByPK(goodsId);
        GoodsAlbum goodsAlbum = new GoodsAlbum();
        goodsAlbum.setGoodsId(goodsId);
        List<GoodsAlbum> goodsAlbums = goodsAlbumService.select(goodsAlbum);
        RebateRatio rebateRatio = new RebateRatio();
        rebateRatio.setGoodsId(goodsId);
        List<RebateRatio> rebateRatios = rebateRatioService.select(rebateRatio);
        if (!ObjectUtils.isEmpty(rebateRatios)) {
            out.put("rebateRatio", rebateRatios.get(0));
        }
        out.put("goods", goods);
        out.put("images", goodsAlbums);
        MsgOut o = MsgOut.success(out);
        return this.renderJson(o);
    }
    
    //查询单个商品信息 带优惠信息 带评论信息
    @RequestMapping(value = "/api/wap/coupon/goods", method = RequestMethod.GET)
    public String wapFindGoodsPage(Long id) {
        if (ObjectUtils.isEmpty(id)) {
            return this.renderJson(MsgOut.error("no data."));
        }
        Goods goods = goodsService.selectByPK(id);

        HashMap map = new HashMap();

        map.put("Goods", goods);

        Coupon coupon = new Coupon();
        coupon.setCompanyId(goods.getGoodsProviderId());
        coupon.setCouponType((byte) 2);
        coupon.setGoodsId(goods.getGoodsId());
        List<Coupon> couponGoods = couponService.select(coupon);

        if (!ObjectUtils.isEmpty(couponGoods)) {
            map.put("CouponGoods", couponGoods);
        }else {
            map.put("CouponGoods", "");
        }

        coupon.setCouponType((byte) 0);
        coupon.setGoodsId(null);
        List<Coupon> couponCompany = couponService.select(coupon);

        if (!ObjectUtils.isEmpty(couponCompany)) {
            map.put("CouponCompany", couponCompany);
        }else {
            map.put("CouponCompany", "");
        }

        Comment comment = new Comment();
        //comment.setCompanyId(goods.getGoodsProviderId());
        comment.setGoodsId(id);
        LOGGER.info("goodsId是：" + comment.getGoodsId());
        long countByTwo = commentService.countByTwo(comment);
        LOGGER.info("个数为：" + countByTwo);
        if (!ObjectUtils.isEmpty(countByTwo)) {
            LOGGER.info("进入计算个数！");
            map.put("commentPl",countByTwo);
        }

        comment.setCommentType((byte) 2);
        List<Comment> commentListMjs = commentService.select(comment);

        if (!ObjectUtils.isEmpty(commentListMjs)) {
            map.put("CommentListMjs", commentListMjs.size());
        }else {
            map.put("CommentListMjs", "");
        }

        MsgOut o = MsgOut.success(map);
        o.setRecords(goods.getRecords());
        o.setTotal(goods.getTotal());
        return this.renderJson(o);
    }
    
    /**
     * 商品编辑页面
     * @param goodsId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/goods/detailsGoods", method = RequestMethod.GET)
    public String detailsGoods(Long goodsId,@RequestHeader(value="headId",required = false) String userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Map map = new HashMap();
        GoodsTypeCustom goodsTypeCustom = new GoodsTypeCustom();
        Goods goods = goodsService.selectByPK(goodsId);
        if (!ObjectUtils.isEmpty(goods.getCustomTypeId())){
            goodsTypeCustom = goodsTypeCustomService.selectByPK(goods.getCustomTypeId());
        }
        GoodsVO goodsVO = new GoodsVO();
        BeanUtils.copyProperties(goods,goodsVO);
        if (!ObjectUtils.isEmpty(goodsTypeCustom)){
            goodsVO.setCustomType(goodsTypeCustom.getName());
        }
        GoodsAlbum goodsAlbum = new GoodsAlbum();
        goodsAlbum.setGoodsId(goodsId);
        goodsAlbum.setImageType((byte)1);
        List<GoodsAlbum> goodsAlbumList = goodsAlbumService.select(goodsAlbum);
        goodsAlbum.setImageType((byte)2);
        List<GoodsAlbum> goodsAlbumList1 = goodsAlbumService.select(goodsAlbum);
        map.put("goods",goodsVO);
        map.put("albumsUrl",goodsAlbumList);
        map.put("detailsAlbumsUrl",goodsAlbumList1);
        return this.renderJson(map);
    }
    
    @RequestMapping(value = "/api/wap/goods/create", method = RequestMethod.POST)
    public String wapCreateGoods(Goods goods, String images) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
//        if (!StringUtils.hasLength(goods.getGoodsSn())) {
//            goods.setGoodsSn(generateSN(goods.getGoodsId()));
//        }
        //供货商类型 0 实体店，1 微商， 8 供货商 127 龙蛙自己的产品
        Company company = companyService.selectByPK(goods.getGoodsProviderId());
        if (!ObjectUtils.isEmpty(company)) {
            goods.setGoodsProviderType(company.getCompanyType());
            goods.setGoodsProviderId(company.getCompanyId());
        }
        if (!ObjectUtils.isEmpty(goods.getGoodsScore())) {
            goods.setGoodsScore(goods.getGoodsScore() * 100);
        }
        JSONArray objects = JSON.parseArray(images);
        GoodsAlbum goodsfirst = JSON.parseObject(objects.get(0).toString(), GoodsAlbum.class);
        goods.setGoodsThum(goodsfirst.getUrl());
        goods = goodsService.insert(goods);
        goods.setGoodsSn(generateSN(goods.getGoodsId()));
        goodsService.update(goods);
        for (int i = 0; i < objects.size(); i++) {
            GoodsAlbum goodsAlbum = JSON.parseObject(objects.get(i).toString(), GoodsAlbum.class);
            goodsAlbum.setGoodsId(goods.getGoodsId());
            goodsAlbumService.insert(goodsAlbum);
        }
        MsgOut o = MsgOut.success(goods);
        return this.renderJson(o);
    }
    
    @RequestMapping(value = "/api/wap/goods", method = RequestMethod.PUT)
    public String wapGoodsUpdate(Goods goods,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(goodsService.update(goods));
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/wap/goods/update", method = RequestMethod.PUT)
    public String wapUpdateGoods(Goods goods, String images) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        goodsService.update(goods);
        JSONArray objects = JSON.parseArray(images);
        GoodsAlbum ga = new GoodsAlbum();
        ga.setGoodsId(goods.getGoodsId());
        List<GoodsAlbum> goodsAlbums = goodsAlbumService.select(ga);
        if (!ObjectUtils.isEmpty(images)) {
            if (!ObjectUtils.isEmpty(goods.getGoodsId()) && goods.getGoodsId() != 0) {
                for (GoodsAlbum where : goodsAlbums) {
                    goodsAlbumService.delete(where.getImageId());
                }
            }
            for (int i = 0; i < objects.size(); i++) {
                GoodsAlbum goodsAlbum = JSON.parseObject(objects.get(i).toString(), GoodsAlbum.class);
                goodsAlbum.setGoodsId(goods.getGoodsId());
                goodsAlbumService.insert(goodsAlbum);
            }
        }
        MsgOut o = MsgOut.success(goodsAlbums);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/wap/updateGoods", method = RequestMethod.PUT)
    public String updateGoods(Goods goods, String imgUrl, String detailePictureUrl, @RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (!ObjectUtils.isEmpty(imgUrl)){
            GoodsAlbum goodsAlbum = new GoodsAlbum();
            goodsAlbum.setGoodsId(goods.getGoodsId());
            goodsAlbum.setImageType((byte)1);
            List<GoodsAlbum> goodsAlbumList = goodsAlbumService.select(goodsAlbum);
            if (!ObjectUtils.isEmpty(goods.getGoodsId())){
                for (GoodsAlbum g : goodsAlbumList){
                    goodsAlbumService.delete(g.getImageId());
                }
            }
            String url[] = imgUrl.split(",");
            goodsAlbum.setImageType((byte)1);
            for (int i = 0; i < url.length; i++) {
                goodsAlbum.setUrl(url[i]);
                goodsAlbumService.insert(goodsAlbum);
            }
        }
        if (!ObjectUtils.isEmpty(detailePictureUrl)){
            GoodsAlbum goodsAlbum = new GoodsAlbum();
            goodsAlbum.setGoodsId(goods.getGoodsId());
            goodsAlbum.setImageType((byte)2);
            //详情图
            List<GoodsAlbum> goodsAlbumList1 = goodsAlbumService.select(goodsAlbum);
            if (!ObjectUtils.isEmpty(goods.getGoodsId())){
                for (GoodsAlbum g : goodsAlbumList1){
                    goodsAlbumService.delete(g.getImageId());
                }
            }
            String detailesUrl[] = detailePictureUrl.split(",");
            goodsAlbum.setImageType((byte)2);
            for (int i = 0; i < detailesUrl.length; i++) {
                goodsAlbum.setImageType((byte)2);
                goodsAlbum.setUrl(detailesUrl[i]);
                goodsAlbumService.insert(goodsAlbum);
            }
        }
        MsgOut o = MsgOut.success(goodsService.update(goods));
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/wap/goods/{goodsId}", method = RequestMethod.DELETE)
    public String wapDeleteGoods(@PathVariable("goodsId") Long goodsId,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(goodsService.delete(goodsId));
        return this.renderJson(o);
    }
    
    /**
     * 商品页中修改图片
     * @param goodsAlbum
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/goods/updateImage", method = RequestMethod.POST)
    public String updateImage(GoodsAlbum goodsAlbum,@RequestHeader(value="headId",required = false) String userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        goodsAlbum.setRstatus((byte)0);
        List<GoodsAlbum> goodsAlbumList = goodsAlbumService.select(goodsAlbum);
        if (goodsAlbumList.size() > 4){
            return this.renderJson(MsgOut.error("Upload up to four pictures."));
        }
        if (!ObjectUtils.isEmpty(goodsAlbum.getUrl())){
            return this.renderJson(MsgOut.success(goodsAlbumService.insert(goodsAlbum)));
        } else {
            return this.renderJson(MsgOut.error("The parameter is empty."));
        }
    }
    
    @RequestMapping(value = "/api/wap/goodsAlbum/{goodsId}", method = RequestMethod.DELETE)
    public String deleteGoodsAlbum(@PathVariable("goodsId") Long imageId,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (!ObjectUtils.isEmpty(imageId)) {
            MsgOut o = MsgOut.success(goodsAlbumService.delete(imageId));
            return this.renderJson(o);
        } else {
            return null;
        }
    }

    @RequestMapping(value = "/api/wap/goodsAlbum", method = RequestMethod.PUT)
    public String deleteGoodsAlbum(GoodsAlbum goodsAlbum) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }

        MsgOut o = MsgOut.success(goodsAlbumService.update(goodsAlbum));
        return this.renderJson(o);
    }
    
    @RequestMapping(value = "/api/wap/goodsAlbum/create", method = RequestMethod.POST)
    public String createGoodsAlbum(GoodsAlbum goodsAlbum, String imgUrl, String detailePictureUrl, @RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        String url[] = imgUrl.split(",");
        String detailesUrl[] = detailePictureUrl.split(",");
        for (int i = 0; i < url.length; i++) {
            goodsAlbum.setUrl(url[i]);
            goodsAlbumService.insert(goodsAlbum);
        }
        for (int i = 0; i < detailesUrl.length; i++) {
            goodsAlbum.setImageType((byte)2);
            goodsAlbum.setUrl(detailesUrl[i]);
            goodsAlbumService.insert(goodsAlbum);
        }
        MsgOut o = MsgOut.success(goodsAlbum);
        return this.renderJson(o);
    }
    
    @RequestMapping(value = "/api/wap/express")
    public String wapEXhTTP(String url) {
        //get请求返回结果
        JSONObject jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.parseObject(strResult);
            } else {
            }
        } catch (IOException e) {

        }
        MsgOut o = MsgOut.success(jsonResult);
        return this.renderJson(o);
    }
    
    /**
     * @api {get} /api/wap/seaElection 公众号-首页海选页面
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/seaElection
     * @apiName seaElection
     * @apiGroup Goods
     * @apiParam {Int} sortType 排序类型.
     * @apiParam {Int} page 第几页.
     * @apiParam {Long} userId 用户Id（headId）.
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     */
    @RequestMapping(value = "/api/wap/seaElection", method = RequestMethod.GET)
    public String seaElection(GoodsVO goodsVO,String cityName,int page,@RequestHeader(value = "headId", required = false) Long userId){
//        if (ObjectUtils.isEmpty(userId)) {
//            return this.renderJson(MsgOut.error("Plz login."));
//        }
        if (!ObjectUtils.isEmpty(cityName)) {
            District district = new District();
            if(cityName.contains("/")){
                String[] citys = cityName.split("/");
                String parentName = citys[0];
                cityName = citys[1];
                district.setName(parentName);
                List<District> districts = districtService.select(district);
                long id = districts.get(0).getId();
                district.setParentid(id);
            }
            district.setName(cityName);
            List<District> districts = districtService.select(district);
            Byte levelType = districts.get(0).getLevelType();
            goodsVO.setPage(page);
            if(levelType == 1){
                goodsVO.setProvince(cityName);
            } else if(levelType == 2){
                goodsVO.setCity(cityName);
            }else{
                goodsVO.setDistrict(cityName);
            }
        }
        goodsVO.setPage(page);
        goodsVO.setGoodsOnline((byte)1);
        List<GoodsVO> goodsList = goodsService.seaElection(goodsVO);
        List<GoodsVO> listOut = new ArrayList<>();
        for(GoodsVO g : goodsList){
            GoodsVO goodsVO1 = new GoodsVO();
            BeanUtils.copyProperties(g,goodsVO1);
            Collection collection = new Collection();
            collection.setGoodsId(g.getGoodsId());
            collection.setCollectionType((byte)1);
            Long collectCount = collectionService.companyCount(collection);
            goodsVO1.setCollectCount(collectCount);
            if(goodsVO1.getXiaoliang() == 0){
                goodsVO1.setXiaoliang(10);
            } else {
                goodsVO1.setXiaoliang(goodsVO1.getXiaoliang() * 50);
            }
            listOut.add(goodsVO1);
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(goodsVO.getRecords());
        o.setTotal(goodsVO.getTotal());
        return this.renderJson(o);
    }
    
    /**
     * 微传媒查询商品
     * @param goods
     * @param page
     * @return
     */
    @RequestMapping(value = "/api/wap/userGoods", method = RequestMethod.GET)
    public String wapGoods(Goods goods, int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        goods.setPage(page);
        goods.setGoodsRecommendSort(1);
        SysUser sysUser = sysUserService.selectByPK(user.getId());
        List<Goods> listOut=new ArrayList<>();
        Company company=companyService.selectByUserId(sysUser.getId());
        if (!ObjectUtils.isEmpty(company)){
            listOut = goodsSearchService.searchForPage(goods);
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(goods.getRecords());
        o.setTotal(goods.getTotal());
        return this.renderJson(o);
    }
    
    
    private String generateSN(Long goodsId) {
        StringBuffer sb = new StringBuffer();
        sb.append(goodsId);
        int zeroLen = 10 - sb.length();
        for (int i = 0; i < zeroLen; i++) {
            sb.insert(0, 0);
        }
        sb.insert(0, "RT");
        return sb.toString();
    }

    /**
     * @api {get} /api/wap/goodsTypeCustom 自定义分类-查询所有
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/goodsTypeCustom
     *
     * @apiName list
     * @apiGroup GoodsTypeCustom
     *
     * @apiParam {String} remark 备注.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {String} name 分类名称.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "id":8,
     *                   "name":"",
     *                   "companyId":0,
     *                   "ctime":1502870415259,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/goodsTypeCustom"
     *  }
     */
    @RequestMapping("/api/wap/goodsTypeCustom")
    public String list(GoodsTypeCustom goodsTypeCustom) {
        if (ObjectUtils.isEmpty(goodsTypeCustom)){
            return this.renderJson(MsgOut.error("查询不到商户"));
        }
        goodsTypeCustom.setCompanyId(goodsTypeCustom.getCompanyId());
        List<GoodsTypeCustom> goodsTypeCustoms=goodsTypeCustomService.select(goodsTypeCustom);
        MsgOut o = MsgOut.success(goodsTypeCustoms);
        return this.renderJson(o);
    }

    /**
     * 商家管理商品（新版）
     * @param goods
     * @param userId
     * @param page
     * @return
     */
    @RequestMapping("/api/wap/companyGods")
    public String companyGods(Goods goods,@RequestHeader(value="headId",required = false) Long userId,int page) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        goods.setPage(page);
        Company company = companyService.selectByCompanyStaff(userId);
        goods.setGoodsProviderId(company.getCompanyId());
        List<Goods> goodsList = goodsService.selectForPage(goods);
        MsgOut o = MsgOut.success(goodsList);
        o.setRecords(goods.getRecords());
        o.setTotal(goods.getTotal());
        return this.renderJson(o);
    }

    /**
     * 带有companyId的商家管理商品（新版）
     * @param goods
     * @param companyId
     * @param page
     * @return
     */
    @RequestMapping("/api/wap/communityGoods")
    public String communityGoods(Goods goods,Long companyId,int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        goods.setPage(page);
        goods.setGoodsProviderId(companyId);
        List<Goods> goodsList = goodsService.selectForPage(goods);
        MsgOut o = MsgOut.success(goodsList);
        o.setRecords(goods.getRecords());
        o.setTotal(goods.getTotal());
        return this.renderJson(o);
    }

    /**
     * 根据goodsId查询商品
     * @param goodsId
     * @return
     */
    @RequestMapping("/api/wap/goodsId")
    public String goods(Long goodsId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(goodsService.selectByPK(goodsId));
        return this.renderJson(o);
    }

    /**
     * 用户查看商品
     * @param goods
     * @param userId
     * @param page
     * @return
     */
    @RequestMapping("/api/wap/userLookGoods")
    public String userLookGoods(Goods goods,@RequestHeader(value="headId",required = false) Long userId,int page) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        goods.setPage(page);
        List<Goods> goodsList = goodsService.selectForPage(goods);
        MsgOut o = MsgOut.success(goodsList);
        o.setRecords(goods.getRecords());
        o.setTotal(goods.getTotal());
        return this.renderJson(o);
    }

    /**
     * 发布商品（新版）
     * @param goods
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/createGoods", method = RequestMethod.POST)
    public String createGoods(Goods goods,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(goods.getGoodsSn())) {
            goods.setGoodsSn(generateSN(goods.getGoodsId()));
        }
        if (goods.getGoodsScreenPrice() == 0) {
            return this.renderJson(MsgOut.error("价格设置不能为0元"));
        }
        //供货商类型 0 实体店，1 微商， 8 供货商 127 龙蛙自己的产品
        Company company = companyService.selectByPK(goods.getGoodsProviderId());
        if (!ObjectUtils.isEmpty(company)) {
            goods.setCategoryId(company.getCompanyTypeId());
            goods.setGoodsProviderType(company.getCompanyType());
            goods.setGoodsProviderId(company.getCompanyId());
        }
        goods = goodsService.insert(goods);
        MsgOut o = MsgOut.success(goods);
        return this.renderJson(o);
    }

    /**
     * 编辑商品页面信息（新版）
     * @param goodsId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/goodsDetail", method = RequestMethod.POST)
    public String goodsDetail(Long goodsId,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Map map = new HashMap();
        Category category = new Category();
        Goods goods = goodsService.selectByPK(goodsId);
        if (!ObjectUtils.isEmpty(goods.getCateId())){
            category = categoryService.selectByPK(goods.getCateId());
        }
        GoodsVO goodsVO = new GoodsVO();
        BeanUtils.copyProperties(goods,goodsVO);
        if (!ObjectUtils.isEmpty(category)){
            goodsVO.setCateName(category.getName());
        }
        GoodsAlbum goodsAlbum = new GoodsAlbum();
        goodsAlbum.setGoodsId(goodsId);
        goodsAlbum.setImageType((byte)1);
        List<GoodsAlbum> goodsAlbumList = goodsAlbumService.select(goodsAlbum);
        goodsAlbum.setImageType((byte)2);
        List<GoodsAlbum> goodsAlbumList1 = goodsAlbumService.select(goodsAlbum);
        map.put("goods",goodsVO);
        map.put("albumsUrl",goodsAlbumList);
        map.put("detailsAlbumsUrl",goodsAlbumList1);
        return this.renderJson(map);
    }

    @RequestMapping(value = "/api/updateCateId", method = RequestMethod.PUT)
    public String updateCateId(Goods goods){
        List<Goods> goodsList = goodsService.select(goods);
        for (Goods g : goodsList){
            Long customTypeId = g.getCustomTypeId();
            if(customTypeId != 0 && !customTypeId.equals("0")){
                GoodsTypeCustom goodsTypeCustom = goodsTypeCustomService.selectByPK(customTypeId);
                g.setCateId(goodsTypeCustom.getCateId());
                goodsService.update(g);
            }
        }
        MsgOut o = MsgOut.success(goodsList);
        return this.renderJson(o);
    }
}
